//
//  WebViewController.m
//  quxiangtao
//
//  Created by xbmios on 2018/8/31.
//  Copyright © 2018年 shanhaijin. All rights reserved.
//

#import "WebViewController.h"
#import <WebKit/WebKit.h>
#import <UShareUI/UShareUI.h>
#import "IntegralRecordViewController.h"
#import "JTNavigationController.h"
#import "ShippingAddressAddViewController.h"
#import "BuyOrderContentDetailViewController.h"
#import "BuyOrderViewController.h"

@interface WebViewController ()<WKUIDelegate, WKNavigationDelegate>

@property (strong, nonatomic) WKWebView *webView;

@property (nonatomic,strong) UIProgressView *progress;
@property (nonatomic,strong) UIBarButtonItem *leftBarButton;
@property (nonatomic,strong) UIBarButtonItem *leftBarButtonSecond;
@property (nonatomic,strong)  UIBarButtonItem *negativeSpacer;
@property (nonatomic,strong)  UIBarButtonItem *negativeSpacer2;


@end

@implementation WebViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.view.backgroundColor = Colorf2f2f2;
    self.automaticallyAdjustsScrollViewInsets = NO;
    [[NSURLCache sharedURLCache] removeAllCachedResponses];
    
    [self.view addSubview:self.webView];
    __weak typeof(self) weakSelf = self;
    [self.webView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(weakSelf.view.mas_left);
        make.right.mas_equalTo(weakSelf.view.mas_right);
        make.top.mas_equalTo(weakSelf.view.mas_top);
        make.bottom.mas_equalTo(0);
    }];
    
    [self.view addSubview:self.progress];
    [self.progress mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.top.mas_equalTo(0);
        make.height.mas_equalTo(1);
    }];
    
    NSURL *requestURL = [NSURL URLWithString:self.url];
    NSURLRequest *request = [[NSURLRequest alloc] initWithURL:requestURL];
    
    if (self.htmlUrl.length < 150) {
        [self.webView loadRequest:request];
    }else {
        NSString *str = [NSString stringWithFormat:@"%@",self.htmlUrl];
        str = [str stringByReplacingOccurrencesOfString:@"\\\"" withString:@"\""];
        str = [str stringByReplacingOccurrencesOfString:@"\\/" withString:@"/"];
        str = [str stringByReplacingOccurrencesOfString:@"\\n" withString:@""];
        str = [str stringByReplacingOccurrencesOfString:@"\\t" withString:@""];
        str = [str stringByReplacingOccurrencesOfString:@"\"" withString:@""];
        str = [str stringByReplacingOccurrencesOfString:@"\\r" withString:@""];
        [self.webView loadHTMLString:str baseURL:nil];
    }
    
    [self addObserver];
    [self setBarButtonItem];
    
}

- (void)webView:(WKWebView *)webView decidePolicyForNavigationResponse:(WKNavigationResponse *)navigationResponse decisionHandler:(void (^)(WKNavigationResponsePolicy))decisionHandler {
    
    WKNavigationResponsePolicy actionPolicy = WKNavigationResponsePolicyAllow;
    decisionHandler(actionPolicy);
}
//chu  没有写回调
- (void)webView:(WKWebView *)webView decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler {
    // 必须实现decisionHandler的回调，否则就会报错
//    if (navigationAction.navigationType == WKNavigationTypeLinkActivated) {
//        decisionHandler(WKNavigationActionPolicyCancel);
//    } else {
//        decisionHandler(WKNavigationActionPolicyAllow);
//    }
    
    WKNavigationActionPolicy actionPolicy = WKNavigationActionPolicyAllow;
    NSString *str = [navigationAction.request.URL absoluteString];
    NSString *url = [NSString stringWithFormat:@"%@",str];
    if ([url containsString:@"invitationqxt://"]) {
        
        NSLog(@"立即邀请");
        [self shareH5Click];

    }
    
    if ([url containsString:@"rollbackfn://"]) {
        
        if (_refreBlock) {
            self.refreBlock(@"0");
        }
        [self.navigationController popViewControllerAnimated:YES];
    }
    // 支付
    if ([url containsString:@"payment://"]) {
        
        NSLog(@"支付");
        
        // 未登录去登录
        if ([CommonUserInfo sharedInstance].isLogin == NO) {
            
            LoginViewController *loginVC = [[LoginViewController alloc] init];
            loginVC.callBackBlock = ^{
                
                
                NSString *s = [NSString stringWithFormat:@"%@%@?userid=%@", ebaseH5,@"bargainHeader.html", [CommonUserInfo sharedInstance].user_id];
                
                NSMutableURLRequest *requeset = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:s]];
                [webView loadRequest:requeset];
                
            };
            JTNavigationController *nav = [[JTNavigationController alloc] initWithRootViewController:loginVC];
            
            [self presentViewController:nav animated:YES completion:nil];
            
            decisionHandler(WKNavigationActionPolicyCancel);
            
            return;
            
        }else {// 已登录
            
            NSDictionary *dict = [self dictionaryWithUrlString:url];
            NSString *addressname = dict[@"addressid"];
            if ([addressname intValue] == 0) {
                
                ShippingAddressAddViewController *vc = [[ShippingAddressAddViewController alloc] init];
                vc.type = 1;
                vc.title = @"添加地址";
                vc.goodsInfoDict = dict;
                [self.navigationController pushViewController:vc animated:YES];
                
            }else {
                
                BuyOrderContentDetailViewController *vc = [[BuyOrderContentDetailViewController alloc] init];
                vc.tradeType = 0;
                vc.dict = dict;
                [self.navigationController pushViewController:vc animated:YES];
                
            }
            
        }
        
    }
    
    // 判断是否登录
    if ([url containsString:@"islogin://"] && [CommonUserInfo sharedInstance].isLogin == NO) {
        
        LoginViewController *loginVC = [[LoginViewController alloc] init];
        loginVC.callBackBlock = ^{
            
            
            NSString *s = [NSString stringWithFormat:@"%@%@?userid=%@", ebaseH5,@"selfSupport.html", [CommonUserInfo sharedInstance].user_id];
            
            NSMutableURLRequest *requeset = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:s]];
            [webView loadRequest:requeset];
            
        };
        JTNavigationController *nav = [[JTNavigationController alloc] initWithRootViewController:loginVC];
        
        [self presentViewController:nav animated:YES completion:nil];
        
        decisionHandler(WKNavigationActionPolicyCancel);
        
        return;
    }
    
    if ([url containsString:@"detailedqdqxt://"]) {
        
        NSLog(@"积分明细");
        
    }
    
    // 砍价分享
    if ([url containsString:@"secondclick://"]) {
        
        
        NSDictionary *dict = [self dictionaryWithUrlString:url];
        
   
        
        [self shareKanjiaClick:dict];
        
    }
    
    // 拼团分享
    if ([url containsString:@"openshow://"]) {
        NSDictionary *dict = [self dictionaryWithUrlString:url];
        
        [self sharePinTuanClick:dict];
        
    }

    
    if ([url containsString:@"https://s.click.taobao.com/t"]) {
    }
    
    //晒图分享
    if ([url containsString:@"printwx://"]) {
        
        NSDictionary *dict = [self dictionaryWithUrlString:url];
        
        [self shareShaiTuClick:dict];
    }

    
    decisionHandler(actionPolicy);
    
}


- (void)sharePinTuanClick:(NSDictionary *)dict {
    WS(weakSelf);
    NSString *string = [NSString stringWithFormat:@"{\"spellid\" : \"%@\"}",[RSA encryptString:dict[@"spellid"] publicKey:PublicKey]];
    [PPNetworkHelper POST:@"groupbuy/groupbuy/appShare" parameters:@{@"json":string} success:^(id responseObject) {
        
        if ([responseObject[@"code"] intValue] == 1) {
            
//            NSString *picStr = @"";
//            if ([responseObject[@"data"][@"photo"] hasPrefix:@"http://"] || [responseObject[@"data"][@"photo"] hasPrefix:@"https://"]) {
//                picStr = responseObject[@"data"][@"photo"];
//            }else {
//                picStr = [NSString stringWithFormat:@"http://%@", responseObject[@"data"][@"photo"]];
//            }
            
            [weakSelf shareWithPartam:responseObject[@"data"][@"title"] Descr:responseObject[@"data"][@"doc"] Photo:responseObject[@"data"][@"photo"] ShareUrl:responseObject[@"data"][@"share_url"] type:@"0"];
        } else {
            
        }
    } failure:^(NSError *error) {
        
    }];
    
}

#pragma  砍价
- (void)shareKanjiaClick:(NSDictionary *) dict {
    WS(weakSelf);
    
    NSString *string = [NSString stringWithFormat:@"{\"userid\" : \"%@\",\"bargain_id\" : \"%@\"}",[RSA encryptString:[CommonUserInfo sharedInstance].user_id publicKey:PublicKey],[RSA encryptString:dict[@"bargain_id"] publicKey:PublicKey]];
    [PPNetworkHelper POST:@"bargain/share/share" parameters:@{@"json":string} success:^(id responseObject) {
        
        if ([responseObject[@"code"] intValue] == 1) {
            
            [weakSelf shareWithPartam:responseObject[@"data"][@"title"] Descr:responseObject[@"data"][@"doc"] Photo:responseObject[@"data"][@"photo"] ShareUrl:responseObject[@"data"][@"share_url"] type:@"0"];
            
        } else {
            
        }
    } failure:^(NSError *error) {
        NSLog(@"请求失败");
    }];
    
    
}
//晒图
- (void)shareShaiTuClick:(NSDictionary *) dict {
    WS(weakSelf);
    
    NSString *string = [NSString stringWithFormat:@"{\"userid\" : \"%@\",\"bargain_id\" : \"%@\"}",[RSA encryptString:[CommonUserInfo sharedInstance].user_id publicKey:PublicKey],[RSA encryptString:dict[@"bargain_id"] publicKey:PublicKey]];
    [PPNetworkHelper POST:@"bargain/share/share" parameters:@{@"json":string} success:^(id responseObject) {
        
        if ([responseObject[@"code"] intValue] == 1) {
            [weakSelf shareWithPartam:responseObject[@"data"][@"title"] Descr:responseObject[@"data"][@"doc"] Photo:responseObject[@"data"][@"photo"] ShareUrl:[NSString stringWithFormat:@"%@showPage.html",ebaseH5] type:@"1"];

//            [weakSelf shareWithPartam:responseObject[@"data"][@"title"] Descr:responseObject[@"data"][@"doc"] Photo:responseObject[@"data"][@"photo"] ShareUrl:responseObject[@"data"][@"share_url"]];
            
        } else {
            
        }
    } failure:^(NSError *error) {
        NSLog(@"请求失败");
    }];
    
    
}
- (void)shareH5Click {
    WS(weakSelf);
     NSString *string = [NSString stringWithFormat:@"{\"userid\" : \"%@\"}",[RSA encryptString:[CommonUserInfo sharedInstance].user_id publicKey:PublicKey]];
    [PPNetworkHelper POST:@"Index/Share/share" parameters:@{@"json":string} success:^(id responseObject) {
        if ([responseObject[@"code"] intValue] == 1) {
            [weakSelf shareWithPartam:responseObject[@"data"][@"title"] Descr:responseObject[@"data"][@"doc"] Photo:responseObject[@"data"][@"photo"] ShareUrl:responseObject[@"data"][@"share_url"] type:@"0"];
        } else {
            
        }
    } failure:^(NSError *error) {
        
    }];
    
    
}


- (void)shareWithPartam:(NSString *)title Descr:(NSString *)descr Photo:(NSString *)photo ShareUrl:(NSString *)shareUrl type:(NSString *)type {
    

    UIImageView *img = [[UIImageView alloc] init];
    [img sd_setImageWithURL:[NSURL URLWithString:photo] placeholderImage:[UIImage imageNamed:@"Qshare"]];
    
    [img sd_setImageWithURL:[NSURL URLWithString:photo] completed:^(UIImage * _Nullable image, NSError * _Nullable error, SDImageCacheType cacheType, NSURL * _Nullable imageURL) {
        
        //创建分享消息对象
        UMSocialMessageObject *messageObject = [UMSocialMessageObject messageObject];
        
        UMShareWebpageObject *shareObject = [UMShareWebpageObject shareObjectWithTitle:title descr:descr thumImage:image];
        shareObject.webpageUrl = shareUrl;
        
        //分享消息对象设置分享内容对象
        messageObject.shareObject = shareObject;
        
        if ([type intValue] == 1) {//区分晒图分享
            [UMSocialUIManager setPreDefinePlatforms:@[@(UMSocialPlatformType_WechatTimeLine)]];
        }else{
        [UMSocialUIManager setPreDefinePlatforms:@[@(UMSocialPlatformType_WechatSession),@(UMSocialPlatformType_WechatTimeLine),@(UMSocialPlatformType_QQ),@(UMSocialPlatformType_Qzone)]];
        }
        
        
        [UMSocialShareUIConfig shareInstance].sharePageGroupViewConfig.sharePageGroupViewPostionType = UMSocialSharePageGroupViewPositionType_Bottom;
        
        [UMSocialUIManager showShareMenuViewInWindowWithPlatformSelectionBlock:^(UMSocialPlatformType platformType, NSDictionary *userInfo) {
            
            //调用分享接口
            [[UMSocialManager defaultManager] shareToPlatform:platformType messageObject:messageObject currentViewController:self completion:^(id data, NSError *error) {
            }];
        }];
        
    }];


    
}

/// 2 页面开始加载
- (void)webView:(WKWebView *)webView didStartProvisionalNavigation:(WKNavigation *)navigation {
}

/// 4 开始获取到网页内容时返回
- (void)webView:(WKWebView *)webView didCommitNavigation:(WKNavigation *)navigation {
}

/// 5 页面加载完成之后调用
- (void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation {
}

#pragma mark -lazy
- (WKWebView *)webView {
    
    if (!_webView) {
        
        _webView = [[WKWebView alloc] init];
        _webView.UIDelegate = self;
        _webView.navigationDelegate = self;
        _webView.backgroundColor = Colorf2f2f2;
        _webView.scrollView.scrollEnabled = YES;
        _webView.scrollView.showsVerticalScrollIndicator = NO;
        _webView.scrollView.showsHorizontalScrollIndicator = NO;
        _webView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
        _webView.multipleTouchEnabled = YES;
        _webView.autoresizesSubviews = YES;
        _webView.scrollView.alwaysBounceVertical = YES;
        _webView.allowsBackForwardNavigationGestures = YES;/**这一步是，开启侧滑返回上一历史界面**/
        if (@available(iOS 11.0 , *)) {
            _webView.scrollView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
        }
    }

    return _webView;
}

#pragma mark 加载进度条
- (UIProgressView *)progress
{
    if (_progress == nil)
    {
        _progress = [[UIProgressView alloc]init];
        _progress.tintColor = Colorff0000;
        _progress.backgroundColor = [UIColor whiteColor];
        [self.view addSubview:_progress];
    }
    return _progress;
}




#pragma mark 添加KVO观察者
- (void)addObserver
{
        //TODO:kvo监听，获得页面title和加载进度值，以及是否可以返回
    [self.webView addObserver:self forKeyPath:@"estimatedProgress" options:NSKeyValueObservingOptionNew context:NULL];
    [self.webView addObserver:self forKeyPath:@"canGoBack" options:NSKeyValueObservingOptionNew context:NULL];
    [self.webView addObserver:self forKeyPath:@"title" options:NSKeyValueObservingOptionNew context:NULL];
}

#pragma mark 设置BarButtonItem
- (void)setBarButtonItem
{
    
        //设置距离左边屏幕的宽度距离
    self.leftBarButton = [[UIBarButtonItem alloc]initWithImage:[UIImage imageNamed:@"nav_go_back"] style:UIBarButtonItemStylePlain target:self action:@selector(selectedToBack)];
    self.negativeSpacer = [[UIBarButtonItem alloc]   initWithBarButtonSystemItem:UIBarButtonSystemItemFixedSpace   target:nil action:nil];
//    self.negativeSpacer.width = 10;
    
    self.leftBarButtonSecond = [[UIBarButtonItem alloc]initWithImage:[UIImage imageNamed:@"close_item"] style:UIBarButtonItemStylePlain target:self action:@selector(selectedToClose)];
    self.leftBarButtonSecond.imageInsets = UIEdgeInsetsMake(0, 0, 0, 0);
    self.navigationItem.leftBarButtonItems = @[self.negativeSpacer,self.leftBarButton];
    self.navigationController.navigationBar.tintColor = Color333333;
    
    UIBarButtonItem *reloadItem = [[UIBarButtonItem alloc]initWithImage:[UIImage imageNamed:@"reload_item"] style:UIBarButtonItemStylePlain target:self action:@selector(selectedToReloadData)];
    self.navigationItem.rightBarButtonItem = reloadItem;
    
}


#pragma mark 关闭并上一界面
- (void)selectedToClose
{
    [self.navigationController popViewControllerAnimated:YES];
}

#pragma mark 返回上一个网页还是上一个Controller
- (void)selectedToBack
{
    if (self.webView.canGoBack == 1)
    {
        [self.webView goBack];
    }
    else
    {
        [self.navigationController popViewControllerAnimated:YES];
    }
}

#pragma mark reload
- (void)selectedToReloadData
{
    [self.webView reload];
}


#pragma mark KVO的监听代理
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context {
    
        //加载进度值
    if ([keyPath isEqualToString:@"estimatedProgress"])
    {
        if (object == self.webView)
        {
            [self.progress setAlpha:1.0f];
            [self.progress setProgress:self.webView.estimatedProgress animated:YES];
            if(self.webView.estimatedProgress >= 1.0f)
            {
                [UIView animateWithDuration:1.5f
                                      delay:0.0f
                                    options:UIViewAnimationOptionCurveEaseOut
                                 animations:^{
                                     [self.progress setAlpha:0.0f];
                                 }
                                 completion:^(BOOL finished) {
                                     [self.progress setProgress:0.0f animated:NO];
                                 }];
            }
        }
        else
        {
            [super observeValueForKeyPath:keyPath ofObject:object change:change context:context];
        }
    }
        //网页title
    else if ([keyPath isEqualToString:@"title"])
    {
        if (object == self.webView)
        {
            self.navigationItem.title = self.webView.title;
        }
        else
        {
            [super observeValueForKeyPath:keyPath ofObject:object change:change context:context];
        }
    }
        //是否可以返回
    else if ([keyPath isEqualToString:@"canGoBack"])
    {
        if (object == self.webView)
        {
            if (self.webView.canGoBack == 1)
            {
                self.navigationItem.leftBarButtonItems = @[self.negativeSpacer,self.leftBarButton,self.leftBarButtonSecond];
            }
            else
            {
                self.navigationItem.leftBarButtonItems = @[self.negativeSpacer,self.leftBarButton];
            }
        }
        else
        {
            [super observeValueForKeyPath:keyPath ofObject:object change:change context:context];
        }
    }
    else
    {
        [super observeValueForKeyPath:keyPath ofObject:object change:change context:context];
    }
}

#pragma mark 移除观察者
- (void)dealloc
{
    [self.webView removeObserver:self forKeyPath:@"estimatedProgress"];
    [self.webView removeObserver:self forKeyPath:@"canGoBack"];
    [self.webView removeObserver:self forKeyPath:@"title"];
}



#pragma mark -设置
- (void)viewWillAppear:(BOOL)animated {
    
    [super viewWillAppear:animated];
    
    self.navigationController.navigationBar.hidden = NO;
//    self.tabBarController.tabBar.hidden = YES;
    
}




- (void)viewWillDisappear:(BOOL)animated {
    
    [super viewWillDisappear:animated];
    [self.webView stopLoading];
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}


-(NSDictionary *)dictionaryWithUrlString:(NSString *)urlStr
{
    if (urlStr && urlStr.length && [urlStr rangeOfString:@"?"].length == 1) {
        NSArray *array = [urlStr componentsSeparatedByString:@"?"];
        if (array && array.count == 2) {
            NSString *paramsStr = array[1];
            if (paramsStr.length) {
                NSMutableDictionary *paramsDict = [NSMutableDictionary dictionary];
                NSArray *paramArray = [paramsStr componentsSeparatedByString:@"&"];
                for (NSString *param in paramArray) {
                    if (param && param.length) {
                        NSArray *parArr = [param componentsSeparatedByString:@"="];
                        if (parArr.count == 2) {
                            [paramsDict setObject:parArr[1] forKey:parArr[0]];
                        }
                    }
                }
                return paramsDict;
            }else{
                return nil;
            }
        }else{
            return nil;
        }
    }else{
        return nil;
    }
}

@end
